package wechat

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"x/server/plugin/logger"
)

const (
	WxXAppID  = "wx305c30b10548d489"
	WxXSecret = "8deda421e8992834b90deeac32d892a7"
)

type AccessTokenResp struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    int64  `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	OpenID       string `json:"openid"`
	Scope        string `json:"scope"`
	UnionID      string `json:"unionid"`
}

func AccessTokenBaseAPI(grantType string, params url.Values) (resp *AccessTokenResp, err error) {
	reqURL := "https://api.weixin.qq.com/sns/oauth2/access_token?"
	if len(params) > 0 {
		reqURL += params.Encode()
		reqURL += "&"
	}
	reqURL += fmt.Sprintf("grant_type=%s", url.QueryEscape(grantType))

	response, err := http.Get(reqURL)
	if err != nil {
		logger.Errorf("request error[%v] url[%s]", err, reqURL)
		return
	}
	defer response.Body.Close()

	bodyByte, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}
	resp = new(AccessTokenResp)
	err = json.Unmarshal(bodyByte, resp)
	return
}

func AuthorizationCode(code string) (resp *AccessTokenResp, err error) {
	params := url.Values{}
	params.Set("appid", WxXAppID)
	params.Set("secret", WxXSecret)
	params.Set("code", code)

	return AccessTokenBaseAPI("authorization_code", params)
}
